package DGWeb.Servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import DGWeb.AppConstants;
import DGWeb.Model.User;

/**
 * Servlet implementation class Profile_Handler
 */
@WebServlet("/Profile_Handler")
public class Profile_Handler extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Profile_Handler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		InputStreamReader isr = new InputStreamReader(request.getInputStream());
		BufferedReader br = new BufferedReader(isr);
		StringBuilder jsonFileContent = new StringBuilder();
		//read line by line from file
		String nextLine = br.readLine();
		jsonFileContent.append(nextLine);
		HttpSession UserSession = request.getSession();
		
		//Boolean Pro = jsonFileContent.toString().contains("Profile"); // true if it has this sub string		
		String UserName=null;
		String whichProfile = (String) UserSession.getAttribute("whichProfile");
		if (whichProfile == (String) UserSession.getAttribute("Username")){
			UserName = (String) UserSession.getAttribute("Username");
		}
		else{
			Context context = null;
			BasicDataSource ds = null;
			Connection conn = null;
			Statement stmt = null;
			java.sql.ResultSet res = null;
			try {
				context = new InitialContext();
				ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
				conn = ds.getConnection();
				//create Customers table
				stmt = conn.createStatement();
				String exec2= "SELECT Username FROM USERS where Nickname='"+whichProfile+"' ";
				res = stmt.executeQuery(exec2);
				while(res.next())
				{
					UserName = res.getString(AppConstants.USERNAME);
				}
				//Release
				res.close();
				conn.commit();
				stmt.close();
				conn.close();
				context.close();
			}
			catch (NamingException |SQLException e) {
				try {
				if (stmt != null)
					stmt.close();
				if (context != null)
					context.close();
				if ( conn != null )
					conn.close();
				if ( res != null )
					res.close();
				} catch (SQLException | NamingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		

			String FoundUser = null, FoundNick = null, FoundMail=null, FoundDescription=null, FoundPhoto=null, IsFollower=null;
			//String[] DataArray = jsonFileContent.toString().split(",");
			//DataArray[0] = DataArray[0].substring(2); // Delete the {" from the begining of the string 
			User U = new User();
			//String[] temp = DataArray[0].split(":");
			
			U.setUsername(UserName);
			
			Context context = null;
			BasicDataSource ds = null;
			Connection conn = null;
			Statement stmt = null;
			java.sql.ResultSet res = null;
			try {
				context = new InitialContext();
				ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
				conn = ds.getConnection();
				//create Customers table
				stmt = conn.createStatement();
				String exec2= "SELECT PHOTO, Description, Nickname, Username, Email FROM USERS where Username='"+U.getUsername()+"' ";
				res = stmt.executeQuery(exec2);
				
				while(res.next())
				{
	    			FoundUser = res.getString(AppConstants.USERNAME);
	    			FoundNick = res.getString(AppConstants.NICKNAME);
	    			FoundMail = res.getString(AppConstants.EMAIL);
	    			FoundDescription = res.getString(AppConstants.DESCRIPTION);
	    			FoundPhoto = res.getString(AppConstants.PHOTO);
				}
			
				//commit update
	    		conn.commit();
	    		stmt.close();
	    		
	    		if ( FoundUser != null && FoundUser.equals(U.getUsername())){
	    			out.print(FoundNick + ",");
	    			out.print(FoundMail + ",");
	    			out.print(FoundDescription + ",");
	    			out.print(FoundPhoto + ",");
	    			out.print(FoundUser + ",");
	    			if (UserName.equals((String) UserSession.getAttribute("Username"))){
	    				out.print("noButton");  //Disable button "Follow" and "UnFollow"  - cause it's my profile.
	    			}
	    			else{
	    				stmt = conn.createStatement();
	    				String exec= "SELECT COUNT(WHO_FOLLOW_USER) as count FROM FOLLOWER where WHO_FOLLOW_USER='" + (String) UserSession.getAttribute("Username") + "' and FOLLOWER_USER='"+U.getUsername()+"' ";
	    				res = stmt.executeQuery(exec);
	    				while(res.next())
	    				{
	    					IsFollower = res.getString("count");
	    				}
	    				if (IsFollower.equals("1")){
	    					out.print("UnFollow");     //Enable button "Unfollow" and disable "Follow" - cause i'm already this member's follower.
	    				}
	    				else{
	    					out.print("Follow");    //Disable button "Unfollow" and enable "Follow" - i'm not a follower of this member.
	    				}
	    			}
	        	}
        		else
        		{
        			out.print("Failed");
        		}
	    		//Release
	    		res.close();
	    		conn.commit();
	    		stmt.close();
	    		conn.close();
	    		context.close();
	    		
			} catch (NamingException |SQLException e) {
				
					try {
					if (stmt != null)
						stmt.close();
					if (context != null)
						context.close();
					if ( conn != null )
						conn.close();
					if ( res != null )
						res.close();
					} catch (SQLException | NamingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
			}
		}
		


}

